<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\ChatRule;
use App\Repository\ArticleRepository;
use App\Repository\ChatRuleRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiChatRuleController extends BaseController4Restful
{
    /**
     * @Route("/api/chatRules", name="apiGetChatRules",methods={"GET","POST"})
     */
    public function apiGetChatRules(ChatRuleRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $ChatRule ChatRule*/
                $ChatRule = $this->createEntity($data,ChatRule::class);
                $this->myEm()->persist($ChatRule);$this->myEm()->flush();
                return $this->json_out(200,"创建成功", $ChatRule);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array(),array(),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/chatRules/{id}", name="apiAddChatRules",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateChatRules(ChatRule $ChatRule,Request $request,ArticleRepository $articleRepository)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($ChatRule);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $ChatRule ChatRule*/
                $ChatRule = $this->updateEntity($data,ChatRule::class,$ChatRule);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($ChatRule);$this->myEm()->flush();
        $this->setGroups("rule","art");

        $ChatRule = $this->serialize($ChatRule);

        foreach ($ChatRule["keywords"] as &$keyword) {
            $keyword["flag"] .="";
        }

        foreach ($ChatRule["reply"] as $key => &$reply) {
            $reply["type"] .="";
            if ($reply["type"] == "article") {
                $art = $articleRepository->find($reply["content"]);
                if (!$art) {
                    unset($ChatRule["reply"][$key]);
                }else{

                    $reply["json"] = $this->serialize($art);
                }
            }
        }
        $ChatRule["replyType"] .="";

        return $this->json_out(200,"获取成功", $ChatRule);
    }
}
